from flask import Blueprint,jsonify,request,abort
from flask_restful import Api,Resource
from app.models import *
# main = Blueprint("main", __name__)
finance = Api()

def convert_list(finance):
    return dict(
        id = finance.id,
        income = finance.income,
        off = finance.off,
        mark = finance.mark

    )

# 财务
class Finance1(Resource):
    def get(self):
        finance = Finance.query.filter(Finance.mark==True).all()
        return jsonify({"finance":list(map(convert_list, finance))})
    def post(self):
        finance_add_one = Finance(
            request.json.get('income'),
            request.json.get('off'),
            request.json.get('mark')

        )
        db.session.add(finance_add_one)
        db.session.commit()
        return jsonify({'finance_add_one': convert_list(finance_add_one)})
finance.add_resource(Finance1, "/finance1/")

class Finance2(Resource):
    def get(self,uid):
        finance_one = Finance.query.filter_by(id=uid,mark=True).first()
        if finance_one is None:
            abort(404)
        return jsonify({'finance_one':convert_list(finance_one)})
    def put(self,uid):
        finance_update = Finance.query.filter_by(id=uid,mark=True).first()
        finance_update.income =request.json.get('income')
        finance_update.off = request.json.get('off')
        finance_update.mark = request.json.get('mark')
        db.session.add(finance_update)
        db.session.commit()
        return jsonify({'finance_update':convert_list(finance_update)})

    def delete(self, uid):
        finance_del = Employment.query.filter_by(id=uid,mark=True).first()
        finance_del.mark = False
        db.session.add(finance_del)
        db.session.commit()
        return jsonify({"result": True})


finance.add_resource(Finance2, "/finance2/<int:uid>/")

